<template>
  <div id="main" style="width: 500px; height: 400px"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, watch, ref } from 'vue';
import { get } from 'lodash';
const props = defineProps({
  eduNeed: {
    type: Object,
    default: () => {},
  },
});
const newEduNeed = ref(null);
const filteredArray = ref(null);
watch(
  () => props.eduNeed,
  (newValue) => {
    if (newValue) {
      newEduNeed.value = newValue;
      filteredArray.value = get(newEduNeed.value, 'edu_ratioStr', []).filter(
        (item) => item.length > 0,
      );

      handleBarChart();
    }
  },
);
const handleBarChart = () => {
  var chartDom = document.getElementById('main');
  var myChart = echarts.init(chartDom);
  var option;

  // There should not be negative values in rawData
  const rawData = filteredArray.value;
  const totalData = [];
  for (let i = 0; i < get(rawData, '[0].length', 1); ++i) {
    let sum = 0;
    for (let j = 0; j < rawData.length; ++j) {
      sum += rawData[j][i];
    }
    totalData.push(sum);
  }
  const grid = {};
  const series = get(newEduNeed.value, 'note', []).map((name, sid) => {
    return {
      name,
      type: 'bar',
      stack: 'total',
      barWidth: '60%',
      label: {},
      data: rawData[sid]?.map((d, did) =>
        totalData[did] <= 0 ? 0 : d / totalData[did],
      ),
    };
  });
  option = {
    title: {
      text: newEduNeed.value.subTitle,
      left: 'left',
      textStyle: {
        fontSize: 16,
      },
    },
    legend: {
      selectedMode: false,
      bottom: 10,
    },
    grid,
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value) => {
          return value * 100 + '%';
        },
      },
    },
    xAxis: {
      type: 'category',
      data: newEduNeed.value.xMarks,
      axisLabel: {
        formatter: (value) => {
          return value + '月';
        },
      },
    },
    series,
  };

  option && myChart.setOption(option);
};
onMounted(() => {});
</script>

<style lang="scss" scoped></style>
